<?php

namespace Home\Controller;

use Common\Controller\MemberBaseController;
use Common\Model\GoodsModel;
use Common\Model\OrderModel;
use Common\Model\OrderPiaofutongModel;
use Common\Model\OrderReturnModel;
use Common\Model\OrderSubModel;
use Think\Controller;
use Vendor\Zhiyoubao\Zhiyoubao\Zhiyoubao;

//class OrderController extends MemberBaseController
class OrderController extends Controller
{
    private $zhiyoubao;

    protected function displayPageList($model, $pageSize = 12, $where = array(), $order = 'id desc')
    {
        $count = $model->where($where)->count();
        $Page = new \Think\Page($count, $pageSize);
        $nowPage = I('p');
        $show = $Page->show();
        $this->assign('page', $show);
        $option = '';
        $pageSelect = '';
        for ($i = 1; $i <= $Page->totalPages; $i++) {
            if (intval($nowPage) == $i)
                $selected = 'selected = "selected"';
            else
                $selected = '';
            $option .= '<option value="' . $i . '" ' . $selected . '>' . $i . '</option>';
        }
        if ($Page->totalPages > 1)
            $pageSelect .= '<form action="" method="get"><select name="p">' . $option . '</select><input type="submit" class="layui-btn layui-btn-normal layui-btn-xs" value="跳转"></form>';
        $this->assign('pageSelect', $pageSelect);
        $list = $model->where($where)->order($order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        return $list;
    }

    function __construct()
    {
        parent::__construct();
        $website = "http://plugin.slit.cn/";
        vendor("Zhiyoubao.Zhiyoubao");
        $this->zhiyoubao = new Zhiyoubao($website);
        session('user_id',366728);
    }

    function detial()
    {
        $order_id = I('get.order_id');
        $model_order = new OrderModel();
        $model_sub_order = new OrderSubModel();
        $model_order_piaofutong = new OrderPiaofutongModel();
        $_list_sub_order = $model_sub_order->where(array('order_id' => $order_id))->select();
        $list_sub_order = [];
        foreach ($_list_sub_order as $sub_order) {
            $_arr = $sub_order;
            $where = array(
                'order_id' => $sub_order['id']
            );
            $_arr['qr'] = $model_order_piaofutong->where($where)->getField('qrcodeurl');
            $list_sub_order[] = $_arr;
        };
        $info = $model_order->find($order_id);
        $this->pay_type = $info['pay_type'];


        $this->assign('info', $info);
        $this->assign('list_sub_order', $list_sub_order);

        $this->display();
    }

    function index()
    {
        $model_order = new OrderModel();
        $act = I('get.act');
        $where = array('user_id' => session('user_id'));
        switch ($act) {
            case 'pay':
                $where['is_pay'] = 1;
                $where['is_return'] = array('neq', 1);
                break;
            case 'nopay':
                $where['is_pay'] = 0;
                $where['is_return'] = array('neq', 1);
                break;
            case 'ok':
                $where['is_status'] = 1;
                break;
            case 'return':
                $where['is_return'] = 1;
                break;
            default:
                break;
        }
        $pageSize = 12;
        $list = $this->displayPageList($model_order, $pageSize, $where, 'addtime desc,id desc');
        $this->assign('list', $list);
        $this->display();
    }

    function qr()
    {
        $order_code = I('get.order_code');
        $req_img = $this->zhiyoubao->getQr($order_code);
        $status = $req_img['status'];
        $info = $req_img['info'];
        if (!$status)
            $this->error($info);
        $model_order = new OrderModel();
        $info_order = $model_order->where(array('order_code' => $order_code))->find();
        $this->assign('info_order', $info_order);
        $this->assign('imgSrc', $info['img']);
        $this->display();
    }

    function return_ticket()
    {
        $data = I('');
        $order_id = $data['order_id'];
        $message = $data['message'];
        $model_order = new OrderModel();
        $model_order_return = new OrderReturnModel();

        $is_order_return = $model_order_return->where(array('order_id' => $order_id))->find();
        if ($is_order_return)
            $this->error('您已经提交过退单申请了，请您耐心等待管理员回馈！');

        $info_order = $model_order->find($order_id);
        // 如果 该订单 为未支付 状态
        if (!$info_order['is_pay']) {
            $add_order_return = array(
                'return_order_code' => OrderReturnModel::get_return_order_code(),
                'user_id' => session('user_id'),
                'order_id' => $info_order['id'],
                'num' => $info_order['num'],
                'message' => trim($message),
                'addtime' => time(),
                'overtime' => time(),
                'status' => 1,
                'is_success' => 1,
                'message' => '未付款订单，自动处理通过！'
            );
            if (!$model_order_return->create($add_order_return))
                $this->error($model_order_return->getError());
            $id_order_return = $model_order_return->add($add_order_return);
            if (!$id_order_return) $this->error('退单 添加 失败！');

            // 修改 订单 is_return 状态 和 order_return 的 overtime 字段
//            $save_is_return = array('is_return' => 1);
//            if (!$model_order->where(array('id' => $order_id))->save($save_is_return))
//                $this->error('退票 状态 修改失败！');
            else
                $this->success('退单 成功！', '/index.php/Home');
        } else {
            $this->display();
        }
        if (IS_POST) {
            $add_order_return = array(
                'return_order_code' => OrderReturnModel::get_return_order_code(),
                'user_id' => session('user_id'),
                'order_id' => $info_order['id'],
                'num' => $info_order['num'],
                'message' => trim($message),
                'addtime' => time()
            );
            if (!$model_order_return->create($add_order_return))
                $this->error($model_order_return->getError());
            $id_order_return = $model_order_return->add($add_order_return);
            if (!$id_order_return) $this->error('退单 添加 失败！');
            else $this->success('退单 申请 成功！请您等待管理员退款！', '/index.php/Home');
            exit();
        }
    }

    function verity_order_ajax()
    {
        $data = I('get.');
        $union_order_num = $data['uniton_order_num'];
        $url = C('MAG_APP_URL') . '/core/pay/pay/orderStatusQuery?unionOrderNum=' . $union_order_num . '&secret=' . C('MAG_SECRET');
        $req = file_get_contents($url);
        $req_arr = json_decode($req, true);
        $this->ajaxReturn($req_arr);
    }

    function verity_order()
    {
        $data = I('get.');
        $union_order_num = $data['uniton_order_num'];
        $url = C('MAG_APP_URL') . '/core/pay/pay/orderStatusQuery?unionOrderNum=' . $union_order_num . '&secret=' . C('MAG_SECRET');
        $req = file_get_contents($url);
        $req_arr = json_decode($req, true);

        $order_model = new OrderModel();
        $where = array(
            'union_order_num' => $union_order_num
        );
        $info_order = $order_model->where($where)->find();
        $is_pay = $info_order['is_pay'];

        if ($is_pay == "0" and $req_arr['code'] == 101) {
            $callback_parm = '/order_code/' . $info_order['order_code'] . '/sign/' . $info_order['sign'];
            $url = C('PROJECT_URL') . 'index.php/Home/Payment/piaofutong_unionOrderNumCallback' . $callback_parm;
            file_get_contents($url);
        }
        $this->redirect('Order/detial', array('order_id' => $info_order['id']));
        exit();
    }
}